#!/usr/local/bin/php
<?php
require_once 'common.php';

/* @var $logger Log */
global $logger;
global $dbOaIIOaWeb;
/* @var $userMigrationTable OpTableModel */
global $userMigrationTable;
/* @var $developerTable OpTableModel */
global $developerTable;

$logger->setMask(Log::MAX(PEAR_LOG_INFO));

$options = getopt('a:f:u:');
if (empty($options)) {
    $logger->err("usage: " . basename(__FILE__) . " [-a import|delete] [-f user_list_file|-u user_id]");
    exit();
}
if (isset($options['a'])) {
    $action = $options['a'];
} else {
    $action = 'import';
}
if (!in_array($action, array('import', 'delete'))) {
    $logger->err("wrong action");
    exit();
}
if (isset($options['f'])) {
    $file = $options['f'];    
    $contents = file_get_contents($file);
    if ($contents === false) {
        $logger->err("get file contents failed");
        exit();
    }
} else if (isset($options['u'])) {
    $userId = $options['u'];
    $sql = "SELECT * FROM TB_USER WHERE ID=:userId";
    $st = oci_parse($dbOaIIOaWeb, $sql);
    oci_bind_by_name($st, ':userId', $userId);
    if (!oci_execute($st)) {
        $e = oci_error($st);
        $logger->err("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
        exit();
    }
    $user = oci_fetch_assoc($st);
    if ($user === false) {
        $logger->err("user not exists: user_id-$userId");
        exit();
    }
    $username = $user['USER_NAME'];
    $result = User::convertId($username);
    if ($result[0] != 0) {
        $logger->err("convert id failed: {$result[1]}");
        exit();
    }
    $uid = $result[2];
    $contents = "$uid\t$username";
} else {
    $logger->err("no file param");
    exit();
}

$rows = explode("\n", trim($contents));
if ($action == 'import') {
    foreach ($rows as $row) {
        $row = explode("\t", trim($row));
        $uid = isset($row[0]) ? $row[0] : '';
        $username = isset($row[1]) ? $row[1] : '';
        $pt = $username;
        $password = '';
        
        // 从TB_USER表读取用户信息
        $sql = "SELECT ID, EMAIL, TRUE_NAME, PHONE, TO_CHAR(CREATE_TIME, 'YYYY-MM-DD HH24:MI:SS') AS CREATE_TIME, 
        	TO_CHAR(LAST_LOGIN_TIME, 'YYYY-MM-DD HH24:MI:SS') AS LAST_LOGIN_TIME 
        	FROM TB_USER WHERE USER_NAME=:username";
        $st = oci_parse($dbOaIIOaWeb, $sql);
        oci_bind_by_name($st, ':username', $username);
        if (!oci_execute($st)) {
            $e = oci_error($st);
            $logger->err("[{$e['code']}] {$e['message']}: {$e['sqltext']}");
            exit();
        }
        $user = oci_fetch_assoc($st);
        if ($user === false) {
            $logger->warning("user not exists: username-$username");
            continue;
        }
        
        // 插入到用户迁移表
        if (!$userMigrationTable->insert(array(
            'username' => $username,
            'user_id' => $user['ID'],
            'pt' => $pt,
            'password' => $password,
            'uid' => $uid,
            'create_time' => date('Y-m-d H:i:s')
        ), null, false)) {
            $logger->warning("insert into user_migration table failed: username-$username");
            continue;
        }
        
        // 插入到开发者表
        if (!$developerTable->insert(array(
            'uid' => $uid,
            'email' => $user['EMAIL'],
            'name' => $user['TRUE_NAME'],
            'phone' => $user['PHONE'],
            'create_time' => $user['CREATE_TIME'],
            'last_login_time' => $user['LAST_LOGIN_TIME'],
            'pt' => $pt
        ), null, false)) {
            $logger->warning("insert into developer table failed: username-$username");
            continue;
        }
        
        $logger->info("import succeed: username-$username");
    }
} else if ($action == 'delete') {
    foreach ($rows as $row) {
        $row = explode("\t", trim($row));
        $uid = isset($row[0]) ? $row[0] : '';
        $username = isset($row[1]) ? $row[1] : '';
        
        if (!$userMigrationTable->delete(array(
            'username' => $username
        ))) {
            $logger->warning("delete from user migration table failed: username-$username");
            continue;
        }
        
        if (!$developerTable->delete(array(
            'uid' => $uid
        ))) {
            $logger->warning("delete from developer table failed: username-$username");
            continue;
        }
        
        $logger->info("delete succeed: username-$username");
    }
}
